package com.lidx.back.statistics.utils;


import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lidx.back.statistics.commons.SpringContextHolder;
import com.lidx.back.statistics.dao.ILogDao;
import com.lidx.back.statistics.dao.impl.LogDaoImpl;
import com.lidx.back.statistics.entity.Log;
public class LogUtils{

	
	private static ILogDao logDao = SpringContextHolder.getBean("logDao");
	
	/**
	 * 保存日志
	 */
	public static void saveLog(HttpServletRequest request, String title){
		saveLog(request, null, null, title);
	}
	
	/**
	 * 保存日志
	 */
	public static void saveLog(HttpServletRequest request, Object handler, Exception ex, String title){
		Log log = new Log();
		log.setType(ex == null ? Log.TYPE_ACCESS : Log.TYPE_EXCEPTION);
		log.setRemoteAddr(StringUtils.getRemoteAddr(request));
		log.setUserAgent(request.getHeader("user-agent"));
		log.setRequestUri(request.getRequestURI());
		log.setParams(request.getParameterMap().toString());
		log.setMethod(request.getMethod());
		log.setCreateDate(new Date());
		log.setOperateUserName(UserUtils.getUser().getLoginName());
		
		// 异步保存日志
		new SaveLogThread(log, handler, ex).start();
	}
	
	/**
	 * 保存日志线程
	 */
	public static class SaveLogThread extends Thread{
		
		
		private Log log;
		private Object handler;
		private Exception ex;
		
		public SaveLogThread(Log log, Object handler, Exception ex){
			super(SaveLogThread.class.getSimpleName());
			this.log = log;
			this.handler = handler;
			this.ex = ex;
		}
		
		@Override
		public void run() {
			// 如果有异常，设置异常信息
			log.setException(Exceptions.getStackTraceAsString(ex));
			// 保存日志信息
			SessionFactory sessionFactory = SpringContextHolder.getBean("sessionFactory");
			Session session = sessionFactory.openSession();
			session.save(log);
			session.close();
		}
	}
}
